package data.deal;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import analyse.SinaIndustrySort;

import dataconnect.ConnectionFactory;

public class SinaIndustryDeal {
	public void deal(String code){
		Document doc = null;
		try {
			doc = Jsoup.connect("http://finance.sina.com.cn/realstock/company/"+code+"/nc.shtml").get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(doc==null){
			return;
		}
		
//		System.out.println(doc.toString());
		
		Elements els = doc.getElementsByClass("com_overview");
		String str = "";
		String area = "";
		for (Element element : els) {
			Elements els2 = element.getElementsByTag("a");
			for (Element element2 : els2) {
				String industry = element2.text();
				if(industry.equals("创业板")||industry.equals("本月解禁")
						||industry.indexOf("深")>=0||industry.indexOf("沪")>=0||industry.indexOf("上证")>=0||industry.indexOf("中小")>=0
						||industry.indexOf("广州")>=0||industry.indexOf("沪")>=0)
					continue;
				if(area.equals("")){
					area=industry;
					continue;
				}
				if(str.equals("")){
					str=str+industry;
				}else{
					str=str+","+industry;
				}
			}
		}
		System.out.println(code);
		System.out.println(area);
		System.out.println(str+"\n");
		Connection con = ConnectionFactory.getConnection();
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			String[] sn = SinaIndustrySort.industry;
			String sql = "update stockinfo set sinaIndustry='"+str+"',area='"+area+"' ";
			for (int i = 0; i < sn.length; i++) {
				if(str.indexOf(sn[i])>-1){
					sql=sql+",sinaIndustry2='"+sn[i]+"'";
					break;
				}
			}
			sql = sql+" where number ='"+code+"'";
			System.out.println(sql);
			stmt.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		SinaIndustryDeal sid = new SinaIndustryDeal();
		String sql = "select number from stockinfo where number not in ('sh000001','sz399001')";
		Connection con = ConnectionFactory.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()){
				sid.deal(rs.getString(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null){
					rs.close();
				}
				if(stmt!=null){
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
//		sid.deal("http://finance.sina.com.cn/realstock/company/sz300355/nc.shtml");
//		System.out.println();
//		sid.deal("http://finance.sina.com.cn/realstock/company/sh600839/nc.shtml");
	}
}
